package cn.itcast.controller.cargo;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ContractProductService;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.utils.FileUploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/cargo/contractProduct")
public class ContractProductController extends BaseController {

    @Reference
    private ContractService contractService;
    @Reference
    private FactoryService factoryService;
    @Reference
    private ContractProductService contractProductService;

    @RequestMapping(value = "/list" ,name = "新增合同下货物并分页展示货物数据")
    public String findAll(String contractId,@RequestParam(value = "page",defaultValue = "1") Integer pageNum , @RequestParam(defaultValue = "10")Integer pageSize){

//        1、用来生产货物的工厂列表
//        2、某一个合同下货物列表分页展示
//        3、当前合同id，为了保存货物时和购销合同关联


 //        1、用来生产货物的工厂列表
//        select * from co_factory where ctype='货物'
        FactoryExample example = new FactoryExample();
        example.createCriteria().andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(example);
        request.setAttribute("factoryList",factoryList);

//        2、查询这个购销合同下的货物 select * from 货物表 where contract_id=??
        ContractProductExample cpExample =  new ContractProductExample();
        cpExample.createCriteria().andContractIdEqualTo(contractId);
        PageInfo pageInfo = contractProductService.findAll(cpExample, pageNum, pageSize);
        request.setAttribute("page",pageInfo);

//        3、当前合同id，为了保存货物时和购销合同关联
        request.setAttribute("contractId",contractId);


       return "cargo/product/product-list";
    }

    @RequestMapping(value = "/toAdd",name = "跳转到新增购销合同页面")
    public String toAdd(){

        return "cargo/contract/contract-add";
    }


    @Autowired
    private FileUploadUtil fileUploadUtil;

    @RequestMapping(value = "/edit",name = "保存购销合同下货物信息")
    public String edit(ContractProduct contractProduct, MultipartFile productPhoto){

        try {
            String picPath = fileUploadUtil.upload(productPhoto);
            contractProduct.setProductImage(picPath);
        } catch (Exception e) {
            System.out.println("图片上传失败..............");
            e.printStackTrace();
        }


        if(StringUtils.isNotEmpty(contractProduct.getId())){
//           id不为空，应该执行修改方法
            contractProductService.update(contractProduct);
        }else{
            contractProduct.setId(UUID.randomUUID().toString());
            contractProduct.setCompanyId(getCompanyId());
            contractProduct.setCompanyName(getCompanyName());
            contractProduct.setCreateTime(new Date()); //创建时间 ,为了方便排序 新的购销合同排到前面
            contractProductService.save(contractProduct);
        }
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractProduct.getContractId(); // 重定向到货物展示列表页面
    }
    @RequestMapping(value = "/toUpdate",name = "跳转到修改购销合同下货物页面")
    public String toUpdate(String id){ // 货物的id
        ContractProduct contractProduct = contractProductService.findById(id);
        request.setAttribute("contractProduct",contractProduct);


//  用来生产货物的工厂列表
//        select * from co_factory where ctype='货物'
        FactoryExample example = new FactoryExample();
        example.createCriteria().andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(example);
        request.setAttribute("factoryList",factoryList);
        return "cargo/product/product-update";
    }
    @RequestMapping(value = "/delete",name = "删除购销合同下货物数据")
    public String delete(String id,String contractId){ // 货物id
        contractProductService.delete(id);
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId; // 重定向到列表页面
    }

    @RequestMapping(value = "/toImport",name = "跳转到上传货物页面")
    public String toImport(String contractId){ // 货物id
        request.setAttribute("contractId",contractId);
        return "/cargo/product/product-import";
    }

/*
    @RequestMapping(value = "/import",name = "批量上传货物方法")
    public String importXls(String contractId,MultipartFile file) throws Exception{ //


        Workbook workbook = new XSSFWorkbook( file.getInputStream()); // 读取磁盘上的excel
//        获取到工作表
        Sheet sheet = workbook.getSheetAt(0);

        int rowIndex = sheet.getLastRowNum();
        Row row = null;
        ContractProduct cp =null;
        List<ContractProduct> productList = new ArrayList<>();
        for (int i = 1; i <= rowIndex; i++) {
            //        获取行
            cp = new ContractProduct();
            row = sheet.getRow(i);
            String factoryName = row.getCell(1).getStringCellValue();
            cp.setFactoryName(factoryName);
            String productNo = row.getCell(2).getStringCellValue();
            cp.setProductNo(productNo);
            Integer cnumber = ((Double)(row.getCell(3).getNumericCellValue())).intValue();
            cp.setCnumber(cnumber);
            String packingUnit = row.getCell(4).getStringCellValue();
            cp.setPackingUnit(packingUnit);
            String loadingRate = ((Double)row.getCell(5).getNumericCellValue()).toString();
            cp.setLoadingRate(loadingRate);
            Integer boxNum =((Double)(row.getCell(6).getNumericCellValue())).intValue();
            cp.setBoxNum(boxNum);
            Double price = (Double)(row.getCell(7).getNumericCellValue());
            cp.setPrice(price);
            String productDesc = row.getCell(8).getStringCellValue();
            cp.setProductDesc(productDesc);
            String productRequest = row.getCell(9).getStringCellValue();
            cp.setProductRequest(productRequest);

//            还需要补充几个值
            cp.setId(UUID.randomUUID().toString());
            cp.setContractId(contractId);

            cp.setCompanyId(getCompanyId());
            cp.setCompanyName(getCompanyName());
            cp.setCreateTime(new Date()); //创建时间 ,为了方便排序 新的购销合同排到前面

            productList.add(cp);


        }
        contractProductService.saveList(productList);

        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }

*/

    @RequestMapping(value = "/import",name = "批量上传货物方法")
    public String importXls(String contractId,MultipartFile file) throws Exception{

        List<ContractProduct> contractProductList = EasyExcel.read(file.getInputStream()).head(ContractProduct.class).sheet(0).doReadSync();
        for (ContractProduct cp : contractProductList) {
            cp.setId(UUID.randomUUID().toString());
            cp.setContractId(contractId);

            cp.setCompanyId(getCompanyId());
            cp.setCompanyName(getCompanyName());
            cp.setCreateTime(new Date()); //创建时间 ,为了方便排序 新的购销合同排到前面
        }
        contractProductService.saveList(contractProductList);

        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }

}
